<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/12/18/018
 * Time: 21:39
 * by 景
 */
//编辑商品
include_once './lib/fun.php';
if(!checkLogin())
{
    msg(2,'亲，您还没有登录，请登录','login.php');
}
//表单进行了提交处理
if(!empty($_POST['name']))
{
    $con = mysqlInit('127.0.0.1','root','root','imooc');
    if(!$goodsId = intval($_POST['id']))
    {
        msg(2,'参数非法');
    }
    //根据商品id校验商品信息
    $sql = "SELECT * FROM `im_goods` WHERE `id` ={$goodsId}";
    $obj = mysqli_query($con,$sql);
    //当根据id查询商品信息为空时  跳转到商品列表页
    if(!$goods = mysqli_fetch_assoc($obj))
    {
        msg(2,'商品不存在','index.php');
    }
    //处理表单数据
    //商品名称
    $name = mysqli_real_escape_string($con,trim($_POST['name']));
    //商品描述
    $des = mysqli_real_escape_string($con,trim($_POST['des']));
    //商品详情
    $content = mysqli_real_escape_string($con,trim($_POST['content']));
    //商品价格
    $price = intval($_POST['price']);
    //验证
    $nameLength = mb_strlen($name,'utf-8');
    if($nameLength<=0||$nameLength>30)
    {
        msg(2,'商品名应该在1-30字符之内');
    }
     if( $price <= 0|| $price >999999999)
     {
         msg(2,'商品价格应该小于999999999');
     }
    $desLength = mb_strlen($des,'utf-8');
    if($desLength <= 0 || $desLength>100)
    {
        msg(2,'商品简介应该在1-100字符之内');
    }
    if(empty($content))
    {
        msg(2,'详情不能为空');
    }
    //更新数组
    $update = array(
        'name' => $name,
        'price' => $price,
        'des' => $des,
        'content' => $content

    );
    //仅当用户选择上传图片时，才对图片进行图片上传处理
    if($_FILES['file']['size']>0)
    {
        $pic = imgUpload($_FILES['file']);
        $update['pic'] =$pic;
    }

    // 只更新被更改的信息
    foreach ($update as $k=>$v)
    {
        if($goods[$k] == $v)
        {
            unset($update[$k]);
        }
    }

    //对比两个数组，如果没有要更新的字段
    if(empty($update))
    {
        msg(1,'操作成功','edit.php?id='.$goodsId);
    }
    //更新sql处理
    $updateSql = '';
    foreach ($update as $k=>$v)
    {
        $updateSql .= "`{$k}` = '{$v}' ,";
    }
    //除去多余的‘，’
    $updateSql = rtrim($updateSql,',');
    unset($sql,$obj,$result);
    $sql = "UPDATE `im_goods` SET {$updateSql} WHERE `id` = {$goodsId}";
    //更新成功
    if($result = mysqli_query($con,$sql))
    {
        msg(1,'操作成功','edit.php?id='.$goodsId);
    }else{
        msg(2,'操作失败','edit.php?id='.$goodsId);
    }

    //var_dump($update);die;
    //var_export($updateSql);die;
    //var_dump($_FILES['file']);die();
}
else
{
     msg(2,'路由非法','index.php');
}